//
//  StartPageView.m
//  QRMaster
//
//  Created by myApple on 15/3/20.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "StartPageView.h"
#import "LineView.h"
#import "PromptInfoView.h"
#import "validateInputValue.h"

@interface StartPageView()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate>
{
    UIButton * languageBtn;
    UILabel * HeaderLabel;
    UITextField * areaTextField;//国家或者地区
    UITextField * UserNameTextField;//账号
    UITextField * PassWordTextField;//密码
    UIButton * ForgetBnt;
    UIButton * LoginBtn;
    UIButton * ResgistBtn;
    UIButton * moreBtn;
    UIButton * seePWDBtn;//查看密码的眼睛
    UIActionSheet * moreSheet;
    
    LineView * areaLine;
    LineView * userNameLine;
    LineView * passWordLine;
    
    BOOL areaCodeFlag;//区号是否正确
    BOOL mobileFlag;//是否填写电话号码
    BOOL passWordFlag;//是否填写密码
    
    UITableView * MoreTableView;
    
    UIView * backView;//黑色遮罩层的view
    NSArray * moreDataArray;
}

@end

#define mainColor  UIColorFromRGB(0x7cd234)
#define UnSelectColor UIColorFromRGB(0xc1c1c1)
#define mainFont   [UIFont systemFontOfSize:13.0]

@implementation StartPageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        areaCodeFlag = YES;
        mobileFlag = NO;
        passWordFlag = NO;
        moreDataArray = @[NSLocalizedString(@"emailLogin", nil),NSLocalizedString(@"tryUse",nil)];
        [self prepareView];
        [self prepareMoreView];
    }
    return self;
}

-(void)prepareView
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
    
    float ScreenWidth = self.frame.size.width;
    float ScreenHeight = self.frame.size.height;
    float x = 22;
    float y = 71;
    float width = ScreenWidth - 2 * x - 100;
    float height = 39;
    //国家或者地区
    areaTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    areaTextField.secureTextEntry = YES;
    areaTextField.userInteractionEnabled = NO;
    areaTextField.delegate = self;
    areaTextField.font = mainFont;
    areaTextField.borderStyle = UITextBorderStyleNone;
    areaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:areaTextField];
    areaLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, ScreenWidth - 32, 0.5)];
    areaLine.backgroundColor = UnSelectColor;
    [self addSubview:areaLine];
    
    HeaderLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 25, 100, 15)];
    HeaderLabel.text = NSLocalizedString(@"areaOrCountry", nil);
    HeaderLabel.font = mainFont;
    areaTextField.leftView = HeaderLabel;
    areaTextField.leftViewMode = UITextFieldViewModeAlways;
    
    _areaTextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _areaTextBtn.frame = CGRectMake(UI_SCREEN_WIDTH - 122, 71, 100, 39);
    [_areaTextBtn setTitle:NSLocalizedString(@"China", nil) forState:0];
    [_areaTextBtn setTitleColor:mainColor forState:0];
    _areaTextBtn.titleLabel.font = mainFont;
    [_areaTextBtn addTarget:self action:@selector(changeArea) forControlEvents:UIControlEventTouchUpInside];
    _areaTextBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self addSubview:_areaTextBtn];
    
    //手机登录
    y += height + 5;
    x = 32;
    width = 60;
    height = 39;
    _areaCodeTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    _areaCodeTextField.font = mainFont;
    _areaCodeTextField.text = @"86";
    _areaCodeTextField.borderStyle = UITextBorderStyleNone;
    _areaCodeTextField.delegate = self;
    _areaCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self addSubview:_areaCodeTextField];
    
    UILabel * addLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, y + 13, 10, 10)];
    addLabel.text = @"+";
    addLabel.textAlignment = NSTextAlignmentRight;
    addLabel.font = mainFont;
    [self addSubview:addLabel];
    
    x = 95;
    width = ScreenWidth - x - 22;
    UserNameTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    UserNameTextField.placeholder = NSLocalizedString(@"loginPromt", nil);
    UserNameTextField.font = mainFont;
    UserNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    UserNameTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self addSubview:UserNameTextField];
    UserNameTextField.delegate = self;
    userNameLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, ScreenWidth - 32, 0.5)];
    userNameLine.backgroundColor = UnSelectColor;
    [self addSubview:userNameLine];
    
    //密码
    y += height + 5;
    width = ScreenWidth - x - 16;
    PassWordTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    PassWordTextField.secureTextEntry = YES;
    PassWordTextField.placeholder = NSLocalizedString(@"passPromt", nil);
    PassWordTextField.delegate = self;
    PassWordTextField.font = mainFont;
    PassWordTextField.borderStyle = UITextBorderStyleNone;
    PassWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:PassWordTextField];
    passWordLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, ScreenWidth - 32, 0.5)];
    passWordLine.backgroundColor = UnSelectColor;
    [self addSubview:passWordLine];
    
//    UIImageView * passWordView = [[UIImageView alloc]initWithFrame:CGRectMake(30, y + 10, 20, 20)];
//    UIImage * passWordImg = [UIImage imageNamed:@"36登录_密码"];
//    passWordView.image = passWordImg;
//    [self addSubview:passWordView];
    UILabel * passWordLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, y + 10, 60, 20)];
    passWordLabel.text = NSLocalizedString(@"passWord", nil);
    passWordLabel.font = mainFont;
    [self addSubview:passWordLabel];
    
    //小眼睛
    UIImageView * oldSeeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    PassWordTextField.rightViewMode = UITextFieldViewModeAlways;
    PassWordTextField.rightView = oldSeeImgView;
    oldSeeImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * oldSeeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seePwd)];
    [oldSeeImgView addGestureRecognizer:oldSeeTap];
    seePWDBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    seePWDBtn.frame = CGRectMake(18, 14, 16, 12);
    seePWDBtn.selected = NO;
    seePWDBtn.userInteractionEnabled = NO;
    [seePWDBtn setBackgroundImage:[UIImage imageNamed:@"Browse"] forState:UIControlStateNormal];
    [seePWDBtn setBackgroundImage:[UIImage imageNamed:@"GreenBrowse"] forState:UIControlStateSelected];
    [oldSeeImgView addSubview:seePWDBtn];
    
    
    x = 16;
    y += height + 26;
    width = ScreenWidth - 2 * x;
    height = 48;
    LoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    LoginBtn.frame = CGRectMake(x, y, width, height);
    [LoginBtn setTitleColor:UIColorFromRGBAndA(0xffffff, 0.5) forState:0];
    [LoginBtn setBackgroundColor:UIColorFromRGBAndA(0x7dc234, 0.5)];
    [LoginBtn setTitle:NSLocalizedString(@"loginBtn", nil) forState:0];
    LoginBtn.layer.cornerRadius = 5;
    LoginBtn.titleLabel.font = [UIFont systemFontOfSize:19.0];
    LoginBtn.enabled = NO;
    [LoginBtn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:LoginBtn];
    
    x = UI_SCREEN_WIDTH - 122;
    width = 100;
    height = 40;
    y += height + 10;
    UIButton * forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetBtn.frame = CGRectMake(x, y, width, height);
    [forgetBtn setTitle:NSLocalizedString(@"forgetBtn", @"忘记密码") forState:0];
    forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    forgetBtn.titleLabel.font = [UIFont systemFontOfSize:11.0];
    [forgetBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    [forgetBtn setBackgroundColor:[UIColor clearColor]];
    [forgetBtn addTarget:self action:@selector(forgetClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:forgetBtn];
    

    x = ScreenWidth / 2.0 - 0.25;
    y = ScreenHeight - 57;
    height = 15;
    width = 0.5;
    LineView * verticalLine = [[LineView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    verticalLine.backgroundColor = UIColorFromRGB(0x333333);
    [self addSubview:verticalLine];
    
    //注册
    x -= 61;
    y += 3;
    height = 14;
    width = 50;
    ResgistBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [ResgistBtn setTitle:NSLocalizedString(@"registBtn", nil) forState:0];
    ResgistBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    ResgistBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [ResgistBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    [ResgistBtn addTarget:self action:@selector(resigstClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:ResgistBtn];
    
    
    //更多
    x = verticalLine.frame.origin.x + verticalLine.frame.size.width + 11;
    width = 80;
    moreBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    moreBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [moreBtn setTitle:NSLocalizedString(@"more", nil) forState:0];
    [moreBtn setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    [moreBtn addTarget:self action:@selector(moreChoose) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:moreBtn];
}


#pragma mark ------------- 准备“更多”的view
-(void)prepareMoreView
{
    backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    backView.hidden = YES;
    backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:backView];
    
    UITapGestureRecognizer * tapBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenBackView)];
    tapBackView.delegate = self;
    [backView addGestureRecognizer:tapBackView];
    
    MoreTableView = [[UITableView alloc]initWithFrame:CGRectMake(40, UI_SCREEN_HEIGHT / 2.0 - 60, UI_SCREEN_WIDTH - 80, moreDataArray.count * 40)];
    MoreTableView.delegate = self;
    MoreTableView.dataSource = self;
    [backView addSubview:MoreTableView];
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    if ([NSStringFromClass([touch.view class]) isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return  YES;
}


#pragma mark ----------uitableviewdelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return moreDataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellID = @"cellId";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.textLabel.text = moreDataArray[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    backView.hidden = YES;
    switch (indexPath.row) {
        case 0:
            [self loginByEmailClick];
            break;
        case 1:
            [self trial];
            break;
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark --------textFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        userNameLine.backgroundColor = mainColor;
    }
    else if (textField == PassWordTextField) {
        passWordLine.backgroundColor = mainColor;
    }
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == PassWordTextField) {
        passWordLine.backgroundColor = UnSelectColor;
        PassWordTextField.text = textField.text;
    }
    else if(textField == UserNameTextField)
    {
        userNameLine.backgroundColor = UnSelectColor;
        UserNameTextField.text = textField.text;
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (_areaCodeTextField == textField)  //判断是否时我们想要限定的那个输入框
    {
        if (range.location >= 4)
        {
            return NO;
        }
        {
            NSString * checkString = _areaCodeTextField.text;
            
            if (![string isEqualToString:@""]) {
                checkString = [checkString stringByAppendingString:string];
            }else{
                //删除的情况
                if (checkString.length >= 1) {
                     checkString=[checkString substringToIndex:(checkString.length - 1)];
                }
            }
            
            int i = 0;
            for (i = 0 ; i < AreaCodeArray.count; i ++) {
                if ([checkString isEqualToString:AreaCodeArray[i]]) {
                    [_areaTextBtn setTitle:AreaArray[i] forState:0];
                    areaCodeFlag = YES;
                    break;
                }
            }
            if (i >= AreaCodeArray.count) {
                [_areaTextBtn setTitle:NSLocalizedString(@"errorAreaOrCountry", nil) forState:0];
                areaCodeFlag = NO;
            }
        }
       
    }
    else if(textField == UserNameTextField)
    {
        if (newString.length > 0) {
            mobileFlag = YES;
        }
        else
        {
            mobileFlag = NO;
        }
    }
    else if (textField == PassWordTextField)
    {
        if (newString.length > 0) {
            passWordFlag = YES;
        }
        else
        {
            passWordFlag = NO;
        }
    }
    [self canTapOfRegist];
    return YES;
}

-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        mobileFlag = NO;
    }
    else if (textField == PassWordTextField)
    {
        passWordFlag = NO;
    }
    [self canTapOfRegist];
    return YES;
}


#pragma mark -------- 切换国家
-(void)changeArea
{
    userNameLine.backgroundColor = RGBA(211, 211, 211, 1);
    areaLine.backgroundColor = RGBA(135, 199, 66, 1);
    passWordLine.backgroundColor = RGBA(211, 211, 211, 1);
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
    if (_delegate && [_delegate respondsToSelector:@selector(choiceArea)]) {
        [_delegate choiceArea];
    }
}


#pragma mark --------- 查看密码
-(void)seePwd
{
    seePWDBtn.selected = !seePWDBtn.selected;
    if (seePWDBtn.selected) {
        PassWordTextField.secureTextEntry = NO;
    }
    else
    {
        PassWordTextField.secureTextEntry = YES;
    }
}

#pragma mark ----------更多选择
-(void)moreChoose
{
//    backView.hidden = NO;
    moreSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil) destructiveButtonTitle:nil otherButtonTitles: NSLocalizedString(@"emailLogin", nil),NSLocalizedString(@"tryUse",nil), nil];
    [moreSheet showInView:self];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self loginByEmailClick];
    }
    else if (buttonIndex == 1)
    {
         [self trial];
    }
}

#pragma mark -------- 点击背景
-(void)hiddenBackView
{
    backView.hidden = YES;
}

#pragma mark -- 试用
-(void)trial
{
    if (_delegate && [_delegate respondsToSelector:@selector(trial)]) {
        [_delegate trial];
    }
}

#pragma mark --------- 邮箱登录
-(void)loginByEmailClick
{
    if (_delegate && [_delegate respondsToSelector:@selector(loginByEamil)]) {
        [_delegate loginByEamil];
    }
}

-(void)forgetClick
{
    if (_delegate && [_delegate respondsToSelector:@selector(ForgetPassWord)]) {
        [_delegate ForgetPassWord];
    }
}


-(void)loginClick:(UIButton *)btn
{
    [self endEditing:YES];
    int i = 0;
    for (i = 0 ; i < AreaCodeArray.count; i ++) {
        if ([_areaCodeTextField.text isEqualToString:AreaCodeArray[i]]) {
            break;
        }
    }
    if (i >= AreaCodeArray.count) {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAreaOrCountry", nil) superView:self];
        return;
    }
    UserNameTextField.text = [UserNameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
    if (![validateInputValue validateStringIsNull:UserNameTextField.text])
    {
        if (![validateInputValue isPureNumandCharacters:UserNameTextField.text])
        {

            [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil)];
            return;
        }
    }
    else
    {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAccount", nil)];
        return;
    }
    
    if (![validateInputValue validatePassword:PassWordTextField.text]) {
        [PromptInfoView showMessage:NSLocalizedString(@"loginingPromt", nil)];
        return;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(Login:PassWord:areaCode:)]) {
        [_delegate Login:UserNameTextField.text PassWord:PassWordTextField.text areaCode:_areaCodeTextField.text];
    }
}

-(void)resigstClick:(UIButton *)btn
{
    if (_delegate && [_delegate respondsToSelector:@selector(Resgsit)]) {
        [_delegate Resgsit];
    }
}

#pragma mark ----------- 判断注册按钮是否能够点击
-(void)canTapOfRegist
{
    if (mobileFlag && areaCodeFlag && passWordFlag) {
        [self loginBtnEnable];
    }
    else
    {
        [self loginBtnDisenable];
    }
}


#pragma mark ----------注册按钮点击和不可以点击的两种状态
-(void)loginBtnEnable
{
    [LoginBtn setBackgroundColor:UIColorFromRGB(0x7cd234)];
    [LoginBtn setTitleColor:UIColorFromRGB(0xffffff) forState:0];
    LoginBtn.enabled = YES;
}

-(void)loginBtnDisenable
{
    [LoginBtn setBackgroundColor:UIColorFromRGBAndA(0x7cd234, 0.5)];
    [LoginBtn setTitleColor:UIColorFromRGBAndA(0xffffff,0.5) forState:0];
    LoginBtn.enabled = NO;
}


-(void)hiddenKeyboard
{
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
}

#pragma mark -- roomNo自适应长度
-(CGFloat)calculateWidth:(NSString *)str
{
    CGSize size =CGSizeMake(self.frame.size.width,20);
    
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:20.0],NSFontAttributeName,nil];
    
    //ios7方法，获取文本需要的size，限制宽度
    
    CGSize  actualsize =[str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    return actualsize.width;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
